package com.webinsky.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.webinsky.web.data.Response;
import com.webinsky.web.utils.WebSessionUtils;

import reactor.core.publisher.Mono;

@Component
public class RequestFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(RequestFilter.class);
	
//	@Autowired
//	private AuthorizationManagement authorizationManagement;
	
	/**
	 * 过滤器 - 检查是否请求是否有session
	 * @param request
	 * @param arg1
	 * @return
	 */
	public Mono<ServerResponse> sessionFilter(ServerRequest request, HandlerFunction<ServerResponse> next){
		return request.session().flatMap(session -> {
			logger.info("[sessionFilter] url = " + request.path());
			if ( WebSessionUtils.getAccount(session) != null ){
				return next.handle(request);
			}
			return ServerResponse.status(HttpStatus.UNAUTHORIZED).syncBody(Response.create("", Response.STATUS_NOTFOUND_ERROR, "用户未登陆"));
		});
	}
	/**
	 * 过滤器 - 检查token
	 * @param request
	 * @param next
	 * @return
	 */
//	public Mono<ServerResponse> tokenFilter(ServerRequest request, HandlerFunction<ServerResponse> next){
//		Optional<String> token  = request.queryParam("token");
//		Optional<String> version = request.queryParam("v");
//		if ( token.isPresent() && version.isPresent() ){
//			User user = authorizationManagement.getAccountByToken(token.get());
//			if ( user != null ){
//				request.attributes().put("Account", user);
//				return next.handle(request);
//			}
//			return ServerResponse.status(HttpStatus.UNAUTHORIZED).syncBody(Response.create("", Response.STATUS_NOTFOUND_ERROR, "token没有找到"));
//		}
//		// token和version是必填项, 否则就报错误
//		return ServerResponse.status(HttpStatus.UNAUTHORIZED).syncBody(Response.create("", Response.STATUS_NOTFOUND_ERROR, "参数错误"));
//	}	
	
}
